package com.qfedu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.entity.Course;
import com.qfedu.entity.ResponseData;
import com.qfedu.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
public class CourseController {

    @Autowired
    private CourseService courseService;

    @RequestMapping("course/addCourse.do")
    public ResponseData addCourse(Course course) {

        int num = courseService.addCourse(course);

        ResponseData responseData = new ResponseData();

        if (num > 0) {
            responseData.setMsg("success");
            responseData.setCode(0);// 0代表成功
        } else {
            responseData.setMsg("fail");
            responseData.setCode(1);// 1 代表失败
        }
        return responseData;
    }


    @RequestMapping("course/coursepage.do")
    public ResponseData<List<Course>> getAllCourse(int page, int limit) {

        // 开启分页
        PageHelper.startPage(page, limit);

        // 按照分页查询
        List<Course> courseList = courseService.getAllCourse();

        PageInfo<Course> coursePageInfo = new PageInfo<>(courseList);

        // 获取数据表中所有数据行数
        int count = (int) coursePageInfo.getTotal();

        ResponseData<List<Course>> responseData = new ResponseData<>();

        // 成功
        responseData.setCode(0);
        responseData.setMsg("success");
        responseData.setCount(count);
        responseData.setData(courseList);

        return responseData;
    }

    @RequestMapping("course/coursedelete.do")
    public ResponseData deleteCourseById(int id) {

        boolean result = courseService.deleteCourseById(id);

        ResponseData responseData = new ResponseData();

        if (result) {
            responseData.setMsg("success");
            responseData.setCode(0);// 0代表成功
        } else {
            responseData.setMsg("fail");
            responseData.setCode(1);// 1 代表失败
        }
        return responseData;
    }

    @RequestMapping("course/courseupdate.do")
    public ResponseData updateCourse(Course course) {
        int num = courseService.updateCourse(course);

        ResponseData responseData = new ResponseData();

        if (num > 0) {
            responseData.setMsg("success");
            responseData.setCode(0);// 0代表成功
        } else {
            responseData.setMsg("fail");
            responseData.setCode(1);// 1 代表失败
        }
        return responseData;
    }
}
